package com.siashan.toolkit.spring.exception;

import com.siashan.toolkit.core.exception.BaseException;
import com.siashan.toolkit.core.wrapper.AjaxResult;
import com.siashan.toolkit.core.wrapper.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * 全局异常处理器
 * 
 * @author siashan
 * @since v1.0.1
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler
{

    /**
     * 基础异常
     *
     * @return 统一异常返回结果
     */
    @ExceptionHandler(BaseException.class)
    public AjaxResult<String> baseException(BaseException e)
    {
        return AjaxResult.error(e.getMessage());
    }



    @ExceptionHandler(NoHandlerFoundException.class)
    public AjaxResult<String> handlerNoFoundException(Exception e)
    {
        log.error(e.getMessage(), e);
        return AjaxResult.error(ResultCode.NOT_FOUND, "路径不存在，请检查路径是否正确");
    }



    @ExceptionHandler(Exception.class)
    public AjaxResult<String> handleException(Exception e)
    {
        log.error(e.getMessage(), e);
        return AjaxResult.error(e.getMessage());
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public AjaxResult<?> validatedBindException(BindException e)
    {
        log.error(e.getMessage(), e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return AjaxResult.error(message);
    }

    /**
     * 自定义验证异常
     *
     * @return 统一异常返回结果
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult<?> validExceptionHandler(MethodArgumentNotValidException e)
    {
        log.error(e.getMessage(), e);
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return AjaxResult.error(message);
    }

}
